﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Data;

namespace BSCore
{
    public class MapEntities:List<MapEntity>
    {

        public MapEntities GetEntitiesByRange(Vector3 fromRange, Vector3 toRange)
        {
          
            MapEntities result = new MapEntities();

            foreach (MapEntity mapEntity in this)
            {
                if (mapEntity.Position.X >= fromRange.X & mapEntity.Position.Y >= fromRange.Y & mapEntity.Position.Z >= fromRange.Z
                    & mapEntity.Position.X <= toRange.X & mapEntity.Position.Y <= toRange.Y & mapEntity.Position.Z <= toRange.Z)
                {
                    
                    result.Add(mapEntity);
                }
            }

            return result;
        }

        public MapEntities GetMapEntitiesOrderedByZ()
        {
            MapEntities result = new MapEntities();
            DataTable dtOrdering = new DataTable();
            dtOrdering.Columns.Add(new DataColumn("X", typeof(float)));
            dtOrdering.Columns.Add(new DataColumn("Y", typeof(float)));
            dtOrdering.Columns.Add(new DataColumn("Z", typeof(float)));
            dtOrdering.Columns.Add(new DataColumn("ID", typeof(int)));

            foreach (MapEntity mapEntity in this)
            {
                DataRow tmpdr = dtOrdering.NewRow();
                tmpdr["X"] = mapEntity.Position.X;
                tmpdr["Y"] = mapEntity.Position.Y;
                tmpdr["Z"] = mapEntity.Position.Z;
                tmpdr["ID"] = mapEntity.ID;
                dtOrdering.Rows.Add(tmpdr);
            }

            //TODO: Sort DataTable
            DataRow[] sortedShizzle = dtOrdering.Select("", "Z ASC");

            foreach (DataRow dr in sortedShizzle)
            {
                foreach (MapEntity mapEntity in this)
                {
                    if (mapEntity.ID == (int)dr["ID"])
                    {
                        result.Add(mapEntity);
                        break;
                    }
                }
            }

            return result;
        }

        public void Draw(GameTime gameTime)
        {
            MapEntities sortedMapEntities = GetMapEntitiesOrderedByZ();
            foreach (MapEntity mapEntity in sortedMapEntities)
            {
                //if (mapEntity is IDrawableMapEntity)
                //{
                //    ((IDrawableMapEntity)mapEntity).Draw(gameTime, ((BSGame)mapEntity.Game).SpriteBatch);

                //}
                mapEntity.Draw(gameTime);

            }
        }

        public void Update(GameTime gameTime)
        {
            foreach (MapEntity mapEntity in this)
            {
                mapEntity.Update(gameTime);
            }
        }
    }
}
